//
//  MapViewController.m
//  PrayerTimes
//
//  Created by Igor Karpenko on 6/8/13.
//  Copyright (c) 2013 Igor Karpenko. All rights reserved.
//

#import "MapViewController.h"
#import "JBTabBarController.h"
#import "ShopAnnotation.h"
#import "CustomAnnotationView.h"
#import "MapTableViewCell.h"

@interface MapViewController ()

@end

@implementation MapViewController

#pragma mark - Instance initialization

-(id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (!self) {
        return nil;
    }
	
	self.title = NSLocalizedString(@"Halal shops", nil);
	self.tabBarItem.image = [UIImage imageNamed:@"gnr_shopsIcon"];
	self.tabBarItem.selectedImage = [UIImage imageNamed:@"gnr_shopsIcon_active"];
	
	_restaurantsItems = [[NSArray alloc] initWithArray:[self getRestaurants]];
	_shopsItems = [[NSArray alloc] initWithArray:[self getGroceryShops]];
	NSMutableArray *array = [NSMutableArray array];
	[array addObjectsFromArray:_restaurantsItems];
	[array addObjectsFromArray:_shopsItems];
	
	_items = [[NSArray alloc] initWithArray:array];
	
	return self;
}


#pragma mark - Memory managment

-(void) dealloc {
	[_restaurantsButton release];
	[_groceryShopsButton release];
	[_mapView release];
	[_tableView release];
	[_tableBackground release];
	[_items release];
	[_restaurantsItems release];
	[_shopsItems release];
	
	[_overlayImage release];
	[super dealloc];
}


#pragma mark - Interface methods

-(void) viewDidLoad {
    [super viewDidLoad];
	_tableBackground.image = [[UIImage imageNamed:@"map_tableBackground"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0f, 20.0f, 0.0f, 20.0f)];
	_overlayImage.image = [_overlayImage.image resizableImageWithCapInsets:UIEdgeInsetsMake(890.0f, 100.0f, 10.0f, 100.0f)];
	
	CGRect newFrame = CGRectMake(2.0f, 2.0f, 316.0f, 74.0f);
	_tableView = [[EasyTableView alloc] initWithFrame:newFrame
									  numberOfColumns:_items.count
											  ofWidth:100.0f];
	_tableView.tableView.backgroundColor = [UIColor clearColor];
	_tableView.tableView.separatorColor = [UIColor clearColor];
	_tableView.delegate = self;
	[self.view addSubview:_tableView];
	
	[_mapView removeAnnotations:_mapView.annotations];
	[_mapView addAnnotations:_restaurantsItems];
}


-(void) viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[self changeLanguage];
}


-(void) viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	
	[self zoomToUserLocation:_mapView.userLocation];

}


-(void) viewDidUnload {
	[self setRestaurantsButton:nil];
	[self setGroceryShopsButton:nil];
	[self setMapView:nil];
	[self setTableView:nil];
	[self setTableBackground:nil];
	[self setOverlayImage:nil];
	[super viewDidUnload];
}


#pragma mark - Action methods

- (IBAction)restaurantsButtonTapped:(id)sender {
	[self deselectItemInTable];
	
	[_mapView removeAnnotations:_mapView.annotations];
	[_mapView addAnnotations:_restaurantsItems];
}


- (IBAction)halalShopsButtonTapped:(id)sender {
	[self deselectItemInTable];
	
	[_mapView removeAnnotations:_mapView.annotations];
	[_mapView addAnnotations:_shopsItems];
}


#pragma mark - Private methods

-(void) zoomToUserLocation:(MKUserLocation *)userLocation {
    if (!userLocation) {
        return;
	}
	
    MKCoordinateRegion region;
    region.center = userLocation.location.coordinate;
    region.span = MKCoordinateSpanMake(2.0, 2.0);
    region = [self.mapView regionThatFits:region];
    [self.mapView setRegion:region animated:YES];
}


-(void) borderIsSelected:(BOOL)selected forView:(UIView *)view {
	NSString *borderImageName = (selected) ? @"map_tableSelectedBackground" : nil;
	view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:borderImageName]];
}


-(NSArray *) getRestaurants {
	ShopAnnotation *shop1 = [[[ShopAnnotation alloc] init] autorelease];
	shop1.title = @"Al Halal Supermarket";
	shop1.address = @"360 Coventry Road \nBirmingham B10 0XE";
	shop1.subtitle = @"0121 753 4391";
	shop1.shopType = ShopTypeRestaurant;
	shop1.imageName = @"magazine1_image";
	shop1.coordinate = CLLocationCoordinate2DMake(52.47183980, -1.86348120);
	
	ShopAnnotation *shop2 = [[[ShopAnnotation alloc] init] autorelease];
	shop2.title = @"National Halal Food Group";
	shop2.address = @"6th Floor 75 Harborne Road, Edgbaston \nBirmingham B15 3DH";
	shop2.subtitle = @"0121 772 2700";
	shop2.fax = @"0121 772 2552";
	shop2.shopType = ShopTypeRestaurant;
	shop2.imageName = @"magazine2_image";
	shop2.coordinate = CLLocationCoordinate2DMake(52.46956840, -1.92864530);
	
	return [NSArray arrayWithObjects:shop1, shop2, nil];
}


-(NSArray *) getGroceryShops {
	ShopAnnotation *shop1 = [[[ShopAnnotation alloc] init] autorelease];
	shop1.title = @"ZAF CASH & CARRY";
	shop1.address = @"55-58, STRATFORD STREET NORTH SPARKBROOK \nBIRMINGHAM B11 1BU";
	shop1.subtitle = @"0121 771 4330";
	shop1.shopType = ShopTypeGroceryShop;
	shop1.imageName = @"magazine3_image";
	shop1.coordinate = CLLocationCoordinate2DMake(52.46834480, -1.87536420);

	ShopAnnotation *shop2 = [[[ShopAnnotation alloc] init] autorelease];
	shop2.title = @"Giro Food Limited";
	shop2.address = @"Welcome House  Glover St \nBirmingham B9 4EP";
	shop2.subtitle = @"0121 773 5811";
	shop2.shopType = ShopTypeGroceryShop;
	shop2.imageName = @"magazine4_image";
	shop2.coordinate = CLLocationCoordinate2DMake(52.47741920, -1.87873970);
	
	return [NSArray arrayWithObjects:shop1, shop2, nil];
}


-(void) deselectItemInTable {
	UIView *cell = [_tableView viewAtIndexPath:_tableView.selectedIndexPath];
	if (cell) {
		[self borderIsSelected:NO forView:cell];
	}
}


-(void) changeLanguage {
	[_restaurantsButton setTitle:AMLocalizedString(@"halalRestaurants", nil) forState:UIControlStateNormal];
	[_groceryShopsButton setTitle:AMLocalizedString(@"halalGroceryShops", nil) forState:UIControlStateNormal];
}


#pragma mark - Map Delegated methods

-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
	CustomAnnotationView *newAnnotation = nil;
	static NSString *annotationReuseIdentifier = @"annotationReuseIdentifier";
	newAnnotation = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationReuseIdentifier];
	if (!newAnnotation) {
		newAnnotation = [[[CustomAnnotationView alloc] initWithAnnotation:annotation
														  reuseIdentifier:annotationReuseIdentifier] autorelease];
	}
	newAnnotation.annotation = annotation;
	newAnnotation.image = [UIImage imageNamed:@"map_pin"];
//	newAnnotation.centerOffset = CGPointMake(-5.0f, -5.0f);
	newAnnotation.canShowCallout = YES;
	
	return newAnnotation;
}



/*-(void) mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
	int index = [_items indexOfObject:view.annotation];
	NSLog(@"%d", index);
	[_tableView selectCellAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]
							 animated:YES];
}


-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
	[_tableView selectCellAtIndexPath:[NSIndexPath indexPathForItem:-1 inSection:0]
							 animated:YES];
}
*/

#pragma mark - EasyTableView Delegated methods

-(UIView *) easyTableView:(EasyTableView *)easyTableView viewForRect:(CGRect)rect {
	MapTableViewCell *cell = [[MapTableViewCell alloc] initWithFrame:rect];
	
	return [cell autorelease];
}


-(void) easyTableView:(EasyTableView *)easyTableView setDataForView:(UIView *)view forIndexPath:(NSIndexPath *)indexPath {
	MapTableViewCell *cell = (MapTableViewCell *)view;
	ShopAnnotation *shop = (ShopAnnotation *)[_items objectAtIndex:indexPath.row];
	cell.titleLabel.text = shop.title;
	cell.detailedLabel.text = shop.address;
	
	BOOL isSelected = (easyTableView.selectedIndexPath) ? ([easyTableView.selectedIndexPath compare:indexPath] == NSOrderedSame) : NO;
	[self borderIsSelected:isSelected forView:view];
}


-(void) easyTableView:(EasyTableView *)easyTableView selectedView:(UIView *)selectedView atIndexPath:(NSIndexPath *)indexPath deselectedView:(UIView *)deselectedView {
	ShopAnnotation *shopForSelect = (ShopAnnotation *)[_items objectAtIndex:indexPath.row];
	for (ShopAnnotation *shop in [_mapView annotations]) {
		if ([shop isEqual:shopForSelect]) {
			[_mapView selectAnnotation:shop animated:YES];
			
			[self borderIsSelected:YES forView:selectedView];
			if (deselectedView) {
				[self borderIsSelected:NO forView:deselectedView];
			}
			break;
		}
	}
	
	
}

@end
